package com.ys.service.purchase.impl;

import com.alibaba.fastjson.JSON;
import com.ys.dto.EditDto;
import com.ys.entity.business.TbBaseInfo;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.hr.ThrOperateCompanyBankInfo;
import com.ys.entity.purchase.TcgPurchaseByOrder;
import com.ys.entity.purchase.TcgPurchaseOrderPay;
import com.ys.entity.sys.TbCompanyBankInfo;
import com.ys.entity.sys.YsCol;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.enume.finance.TcwAccountCountForWanliEnum;
import com.ys.enume.finance.TcwFinancialTransactionFlowEnum;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.purchase.TcgPurchaseByOrderEnum;
import com.ys.mapper.product.ProductMapper;
import com.ys.mapper.purchase.TcgPurchaseByOrderMapper;
import com.ys.mapper.purchase.TcgPurchaseOrderPayMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.finance.TcwAccountCountForWanliService;
import com.ys.service.finance.TcwFinancialTransactionFlowService;
import com.ys.service.purchase.Api1688Service;
import com.ys.service.purchase.TcgPurchaseOrderPayService;
import com.ys.util.CheckUtil;
import com.ys.util.ToolUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 采购付款
 */
@Service("tcgPurchaseOrderPayService")
public class TcgPurchaseOrderPayServiceImpl implements TcgPurchaseOrderPayService {
	private static final Logger logger = LoggerFactory.getLogger(TcgPurchaseOrderPayServiceImpl.class);

	@Autowired
	private TcgPurchaseByOrderMapper tcgPurchaseByOrderMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private Api1688Service api1688Service;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private TcgPurchaseOrderPayMapper tcgPurchaseOrderPayMapper;

	@Autowired
	private TcwAccountCountForWanliService tcwAccountCountForWanliService;

	@Autowired
	private TcwFinancialTransactionFlowService tcwFinancialTransactionFlowService;

	@Autowired
	private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;



	//审核
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R examine(String choooseDatas) throws Exception{
		//根据付款表id去重
		List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(JSON.parseArray(choooseDatas),e->e.get("id").toString());

		int doCount = 0;
		String resMsg = "";
		//获取可审核的状态信息
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getExaminePayStatus();

		for (int i = 0; i < detailList.size(); i++) {
			Map<String, Object> info = detailList.get(i);
			R res = null;

			TcgPurchaseByOrder tcgPurchaseOrder = null;
			//验证
			TcgPurchaseOrderPay tcgPurchaseOrderPay = new TcgPurchaseOrderPay().setId(Long.parseLong(info.get("id").toString())).queryFirst();
			if(tcgPurchaseOrderPay==null || tcgPurchaseOrderPay.getBid()==null){
				res = R.error("未查询到要审核的采购付款信息");
			}else {
				tcgPurchaseOrder = new TcgPurchaseByOrder().setBid(tcgPurchaseOrderPay.getPurchaseOrderBid()).queryFirst();
				if(tcgPurchaseOrder==null || tcgPurchaseOrder.getBid()==null){
					res = R.error("未查询到要审核的采购订单信息");
				}else {

					//验证状态
					boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,tcgPurchaseOrder.getOrderStatus());
					//验证状态
					if(!statusIsPass){
						res = R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的付款单才可进行审核");
					}
					//验证付款方式
					if(checkUtil.isNullByObject(tcgPurchaseOrderPay.getPayType())){
						res = R.error("请先选择付款方式后再进行审核");
					}
				}
			}

			//处理
			if(res == null && tcgPurchaseOrder!=null){
				res = doExamine(tcgPurchaseOrderPay,tcgPurchaseOrder);
			}

			//返回
			if(res.getCode()==0){
				doCount ++;
			}else{
				resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
			}
		}
		resMsg = "成功审核"+doCount+"条付款信息</br>"+resMsg;
		return R.ok(resMsg);
	}


	//审核
	public R doExamine(TcgPurchaseOrderPay tcgPurchaseOrderPay,TcgPurchaseByOrder tcgPurchaseOrder) throws Exception{
		if(checkUtil.isNullByObject(tcgPurchaseOrderPay.getChargeTrouble()) && tcgPurchaseOrderPay.getPayType() == 1){
			return R.error("付款手续费等信息尚未刷新，请稍等片刻后重新审核！");
		}

		//付款方式对应流水 =》 跨境宝（万里汇流水）、支付宝（财务流水）
		//备注
		String remark = tcgPurchaseOrderPay.getBid()+"，"+tcgPurchaseOrder.getAliOrderNumber();//采购付款单号号，1688订单编号
		if(tcgPurchaseOrderPay.getPayType() == 0){//支付宝
			//获取交易类型
			String transactionTypeStr = TransactionTypeEnum.BusinessType.CGFW_CGCBZC.name;
			TbBaseInfo transactionTypeItem = tcwFinancialTransactionFlowService.getTransactionType(transactionTypeStr);
			//获取银行账户信息
			TbCompanyBankInfo tbCompanyBankInfo = new TbCompanyBankInfo().setVid(tcgPurchaseOrderPay.getVid()).queryFirst();
			if(tbCompanyBankInfo==null || tbCompanyBankInfo.getId()==null){
				return R.error("未查询到对应的银行账户信息");
			}

			if(transactionTypeItem!=null && transactionTypeItem.getId()!=null){
				R res = tcwFinancialTransactionFlowService.add(true, tbCompanyBankInfo.getId(),
						transactionTypeItem.getBid(),"1688采购平台", "1688采购平台", "1688采购平台",
						tcgPurchaseOrder.getOrderAmount().negate(),
						tcgPurchaseOrderPay.getCreateTime(),new Date(),new Date(),remark,
						TcwFinancialTransactionFlowEnum.FromType.TCG_PurchaseOrderPay.value,tcgPurchaseOrderPay.getId());
				if(res.getCode().equals(R.Code.FAILED.value)){//失败
					String reeorMsg = res.getMsg();
					logger.info("新增万里汇流水失败:"+reeorMsg);
					throw new IllegalArgumentException(reeorMsg);
				}
			}

		}else {//跨境宝
			//新增万里汇流水
			//1、-实际订单金额（含运）
			R res1 = tcwAccountCountForWanliService.add(true,"ZHBM00001", "CNH",TcwAccountCountForWanliEnum.DocumentType.TCG_PurchaseOrderPay.value,
					tcgPurchaseOrderPay.getBid(),tcgPurchaseOrder.getOrderAmount().negate(), remark);
			//2、-1688付款手续费
			R res2 = tcwAccountCountForWanliService.add(true,"ZHBM00001", "CNH",TcwAccountCountForWanliEnum.DocumentType.TCG_PurchaseOrderPay.value,
					tcgPurchaseOrderPay.getBid(),tcgPurchaseOrderPay.getChargeTrouble().negate(), remark);
			//3、-WF付款手续费
			R res3 = tcwAccountCountForWanliService.add(true,"ZHBM00001", "CNH",TcwAccountCountForWanliEnum.DocumentType.TCG_PurchaseOrderPay.value,
					tcgPurchaseOrderPay.getBid(),tcgPurchaseOrderPay.getChargeTroubleWf().negate(), remark);

			if(res1.getCode().equals(R.Code.FAILED.value) || res2.getCode().equals(R.Code.FAILED.value) || res3.getCode().equals(R.Code.FAILED.value)){//失败
				String reeorMsg = "";
				if(res1.getCode().equals(R.Code.FAILED.value)) reeorMsg = res1.getMsg();
				if(res2.getCode().equals(R.Code.FAILED.value)) reeorMsg = res2.getMsg();
				if(res3.getCode().equals(R.Code.FAILED.value)) reeorMsg = res3.getMsg();

				logger.info("新增万里汇流水失败:"+reeorMsg);
				throw new IllegalArgumentException(reeorMsg);
			}
		}


		//业务流水
		//1、-实际订单金额（含运）
		R res1 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
				"GS0607","采购部", "1688", "1688采购平台",
				TransactionTypeEnum.BusinessType.CGFW_CGCBZC.name, tcgPurchaseOrder.getOrderAmount().negate(),
				tcgPurchaseOrderPay.getCreateTime(), new Date(),remark,tcgPurchaseOrderPay.getBid(),new Date());
		//2、-1688付款手续费
		R res2 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
				"GS0607","采购部", "1688", "1688采购平台",
				TransactionTypeEnum.BusinessType.CGFW_SXF.name, tcgPurchaseOrderPay.getChargeTrouble().negate(),
				tcgPurchaseOrderPay.getCreateTime(), new Date(),remark+"，"+tcgPurchaseOrderPay.getChargeTrouble(),tcgPurchaseOrderPay.getBid(),new Date());
		//3、-WF付款手续费
		R res3 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
				"GS0607","采购部", "WorldFirst", "WorldFirst支付平台",
				TransactionTypeEnum.BusinessType.CGFW_SXF.name, tcgPurchaseOrderPay.getChargeTroubleWf().negate(),
				tcgPurchaseOrderPay.getCreateTime(), new Date(),remark+"，"+tcgPurchaseOrderPay.getChargeTroubleWf(),tcgPurchaseOrderPay.getBid(),new Date());

		if(res1.getCode().equals(R.Code.FAILED.value) || res2.getCode().equals(R.Code.FAILED.value) || res3.getCode().equals(R.Code.FAILED.value)){//失败
			String reeorMsg = "";
			if(res1.getCode().equals(R.Code.FAILED.value)) reeorMsg = res1.getMsg();
			if(res2.getCode().equals(R.Code.FAILED.value)) reeorMsg = res2.getMsg();
			if(res3.getCode().equals(R.Code.FAILED.value)) reeorMsg = res3.getMsg();
			logger.info("新增业务流水失败:"+reeorMsg);
			throw new IllegalArgumentException(reeorMsg);
		}


		//修改订单状态
		tcgPurchaseOrder.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PAY_FINISH.value);
		tcgPurchaseByOrderMapper.update(tcgPurchaseOrder);

		//记录审核人
		tcgPurchaseOrderPay.setAuditingTime(new Date());
		tcgPurchaseOrderPay.setAuditingUserId(ShiroUtils.getUserId());
		tcgPurchaseOrderPayMapper.update(tcgPurchaseOrderPay);

		return R.ok();

	}





	//取消付款
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R cancel(String choooseDatas,String cancelType) throws Exception{
		//根据付款id去重
		List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(JSON.parseArray(choooseDatas),e->e.get("id").toString());

		int doCount = 0;
		String resMsg = "";
		for (int i = 0; i < detailList.size(); i++) {
			Map<String, Object> info = detailList.get(i);
			R res = null;

			TcgPurchaseByOrder tcgPurchaseOrder = null;
			//验证
			TcgPurchaseOrderPay tcgPurchaseOrderPay = new TcgPurchaseOrderPay().setId(Long.parseLong(info.get("id").toString())).queryFirst();

			//获取可取消的状态信息
			List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getCancelPayStatus();

			if(tcgPurchaseOrderPay==null || tcgPurchaseOrderPay.getBid()==null){
				res = R.error("未查询到要取消的采购付款信息");
			}else {
				tcgPurchaseOrder = new TcgPurchaseByOrder().setBid(tcgPurchaseOrderPay.getPurchaseOrderBid()).queryFirst();
				if(tcgPurchaseOrder==null || tcgPurchaseOrder.getBid()==null){
					res = R.error("未查询到要取消的采购订单信息");
				}else {
					//验证状态
					boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,tcgPurchaseOrder.getOrderStatus());
					//验证状态
					if(!statusIsPass){
						res = R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的付款单才可取消");
					}
				}
			}

			if(res == null && tcgPurchaseOrder!=null){
				//处理
				if(cancelType.equals("0")){//按计划
					res = cancelByPlan(tcgPurchaseOrder);
				}else{
					res = cancelByOrder(tcgPurchaseOrder);
				}
			}

			//返回成功与否
			if(res.getCode()==0){
				doCount ++;
			}else{
				resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
			}
		}
		resMsg = "成功取消"+doCount+"条付款数据</br>"+resMsg;
		return R.ok(resMsg);
	}


	//取消付款 - 按订单
	public R cancelByOrder(TcgPurchaseByOrder tcgPurchaseOrder) throws Exception{
		tcgPurchaseOrder.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PAY_CANCEL.value);
		doBackFlow(tcgPurchaseOrder);
		tcgPurchaseByOrderMapper.update(tcgPurchaseOrder);
		return R.ok();
	}

	//取消付款 - 按计划 =》 改：按计划+商品母件
	public R cancelByPlan(TcgPurchaseByOrder tcgPurchaseOrder) throws Exception{
		String errorMsg = "";
		//根据计划单号，获取所有对应的采购订单信息
		List<TcgPurchaseByOrder> orderListByPlanBid = new TcgPurchaseByOrder()
				.setPlanBid(tcgPurchaseOrder.getPlanBid())
				.setPurchasePlanGoodsId(tcgPurchaseOrder.getPurchasePlanGoodsId())
				.setStatus(1)
				.queryList();
		if(orderListByPlanBid!=null && orderListByPlanBid.size()>0){

			//获取可取消的状态信息
			List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getCancelPayStatus();

			//验证采购订单是否都可取消
			for(TcgPurchaseByOrder entity:orderListByPlanBid){
				//验证状态
				boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,entity.getOrderStatus());
				//验证状态
				if(!statusIsPass){
					errorMsg += "订单号："+entity.getBid()+"的状态是："+TcgPurchaseByOrderEnum.OrderStatus.getName(entity.getOrderStatus())+"不可取消！";
				}
			}

			//如果有错误信息，则返回
			if(!"".equals(errorMsg)){
				return R.error(errorMsg);
			}

			//取消对应的所有采购订单信息
			for(TcgPurchaseByOrder entity:orderListByPlanBid){
				entity.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PAY_CANCEL.value);
				doBackFlow(entity);
				tcgPurchaseByOrderMapper.update(entity);
			}

		}
		return R.ok();

	}


	//取消时做方向流水
	public R doBackFlow(TcgPurchaseByOrder tcgPurchaseOrder)throws Exception{
		TcgPurchaseOrderPay entity = new TcgPurchaseOrderPay().setPurchaseOrderBid(tcgPurchaseOrder.getBid()).queryFirst();
		//重新冻结 解冻的金额
		tcwAccountCountForCompanyService.frozen(tcgPurchaseOrder.getVgsbm(), tcgPurchaseOrder.getOrderAmountExpect(),
				TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseOrderPay.value,
				entity.getId(),
				entity.getBid(),
				null);

		TpProductActive tpProductActive = new TpProductActive().setCode(tcgPurchaseOrder.getSpBm()).queryFirst();
		String remark = "【订单取消】" + tcgPurchaseOrder.getBid()+","+tcgPurchaseOrder.getSpBm()+tpProductActive.getName();
		//新增业务流水
		//实际订单金额（含运
		tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(
				tcgPurchaseOrder.getVgsbm(), "GS0607",
				TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name,
				tcgPurchaseOrder.getPurchaseOrderAmount(),
				tcgPurchaseOrder.getCreateTime(),new Date(),
				remark,
				tcgPurchaseOrder.getBid(), new Date());
		tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(
				"GS0607",tcgPurchaseOrder.getVgsbm(),
				TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name,
				tcgPurchaseOrder.getPurchaseOrderAmount().negate(),
				tcgPurchaseOrder.getCreateTime(),new Date(),
				remark,
				tcgPurchaseOrder.getBid(), new Date());

		//采购服务费
		tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(
				tcgPurchaseOrder.getVgsbm(), "GS0607",
				TransactionTypeEnum.BusinessType.CGFW_DLCGFWF.name,
				tcgPurchaseOrder.getServiceCharge(),
				tcgPurchaseOrder.getCreateTime(),new Date(),
				remark,
				tcgPurchaseOrder.getBid(), new Date());
		tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(
				"GS0607",tcgPurchaseOrder.getVgsbm(),
				TransactionTypeEnum.BusinessType.CGFW_DLCGFWF.name,
				tcgPurchaseOrder.getServiceCharge().negate(),
				tcgPurchaseOrder.getCreateTime(),new Date(),
				remark,
				tcgPurchaseOrder.getBid(), new Date());

		return R.ok();

	}



	/**
	 * 修改
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		String payIds = params.get("payIds").toString();
		String[] idArr = payIds.split(",");
		for(String idStr:idArr){
			//遍历修改
			TcgPurchaseOrderPay entity = JSON.parseObject(JSON.toJSONString(params), TcgPurchaseOrderPay.class);
			entity.setId(Long.parseLong(idStr));
			if(entity.getPayType()==0){//支付宝
				//手续费填为0
				entity.setChargeTroubleWf(BigDecimal.ZERO);
				entity.setChargeTrouble(BigDecimal.ZERO);
			}
			tcgPurchaseOrderPayMapper.update(entity);
		}

		String goodsIds = params.get("goodsIds").toString();

		//获取可以进行付款的状态
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getPayStatus();
		//拼接
		String orders = TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList);


		//过滤，只有付款失败和订单待付款的，才可进行付款
		List<Map<String, Object>> groupsByList = new TcgPurchaseOrderPay()
				//.where("A.PurchasePlanGoodsId IN ("+goodsIds+")")
				.where("A.Id IN ("+payIds+")")
				.addLeftJoin("TCG_PurchaseByOrder B ON A.PurchaseOrderBid = B.Bid")
				.addField("B.AliOrderNumber AS aliOrderNumber")
				.where("B.OrderStatus IN ("+orders+")")
				.queryMap();
		//去重
		List<Map<String, Object>> resListByGroups = ToolUtil.groupsByList(groupsByList, e->e.get("id").toString());
		String aliOrderNos = "";
		for(Map<String, Object> item:resListByGroups){
			if("".equals(aliOrderNos)){
				aliOrderNos = item.get("aliOrderNumber").toString();
			}else {
				aliOrderNos += "," + item.get("aliOrderNumber").toString();
			}
		}
		R res = api1688Service.get1688AlipayUrl(aliOrderNos);
		if(res.getCode().equals(R.Code.SUCCESS.value)){
			return R.ok(EditDto.openNewPage(res.get("data").toString()));
		}else {
			logger.info("生成链接失败:"+res.getMsg());
			throw new IllegalArgumentException(res.getMsg());
		}


	}



	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TCG_PurchaseOrderPay",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		return backMsg;
	}


}
